import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:spring_fairy/api/api.dart';
import 'package:spring_fairy/api/user_api.dart';
import 'package:spring_fairy/model/user.dart';


class UserStore {
  static bool hasLogin = false;

  static User? user;

  static String? token;

  static VoidCallback? onLoginStateChange;

  static final UserAPI _userAPI = UserAPI();


  //将用户信息写入文件保持
  static Future<void> saveToFile() async {
    if(user == null || token == null) {
      return ;
    }

   var supportDir = await getApplicationSupportDirectory();
    var filePath = join(supportDir.path,"user.config");
    var map = {
      "user":user!.toJson(),
      "token":token
    };

    File file = File(filePath);
    if(!file.existsSync()) {
      file.createSync();
    }
    await file.writeAsString(json.encode(map));
    print("写入完成:${file.resolveSymbolicLinksSync()}");
    print("=================");
  }

  static Future<bool> readFromFile() async {
    var supportDir = await getApplicationSupportDirectory();
    var filePath = join(supportDir.path,"user.config");
    File file = File(filePath);

    if(!file.existsSync()) {
      return false;
    }
    try {
      var map = json.decode(file.readAsStringSync());
      User user = User.fromJson(map['user']);
      String token = map['token'];
      UserStore.user = user;
      UserStore.token = token;
      API.token = token;

      User? currentUser = await _userAPI.info();
      if(currentUser == null) {
        UserStore.user = null;
        UserStore.token = null;
        API.token = null;
        return false;
      } else {
        UserStore.user = currentUser;
      }

      UserStore.hasLogin = true;
      return true;
    } catch(err,stack) {
      debugPrint(err.toString());
      debugPrintStack(stackTrace: stack);
      return false;
    }
  }
}